﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Data;

namespace MVCApplication.Helpers
{
    public static class HtmlHelperExtensions
    {
        public static string DatePicker(this HtmlHelper helper, string name, object date, bool appendJS, bool readOnly, System.Web.UI.Page page)
        {
            StringBuilder html = new StringBuilder();
            // Model Binding Support    
            string dateValue = null;
            if (date != null)    
            {
                if (date is DateTime? && ((DateTime)date) != DateTime.MinValue)
                    dateValue = ((DateTime)date).ToShortDateString();
                else if (date is DateTime && (DateTime)date != DateTime.MinValue)
                    dateValue = ((DateTime)date).ToShortDateString();
                else if (date is string)
                    dateValue = (string)date;
            }
            // Build our base input element    
            html.Append(helper.TextBox(name, dateValue, "formText", "8", "10", readOnly, "formTextView", false, "", false));
            // We're hard-coding the width here, a better option would be to pass in html attributes and reflect through them    
            // Now we call the datepicker function, passing in our options.  Again, a future enhancement would be to  
            // pass in date options as a list of attributes ( min dates, day/month/year formats, etc. )  

            if (appendJS)
            {
                html.Append("<script type=\"text/javascript\">");
                html.Append(DatePickerJS(helper, name, page));
                html.Append("</script>");
            }
            return html.ToString();
        }
        
        public static string DateTimePicker(this HtmlHelper helper, string name, object date, bool appendJS, bool readOnly, System.Web.UI.Page page)
        {
			return helper.DatePicker(name, date, appendJS, readOnly, page);
        }

        public static string DatePickerJS(this HtmlHelper helper, string name, System.Web.UI.Page page)
        {
            string imageUrl = GeneralFunctions.GetThemePath(page) + "Images/calendar.gif";
            System.Globalization.DateTimeFormatInfo dtfi = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;
            string dateFormat = dtfi.ShortDatePattern.Replace("MM", "mm").Replace("yyyy", "yy");
            return "$(document).ready(function() { $('#" + name + "').datepicker({ dateFormat: '" + dateFormat + "', buttonImageOnly: true, showOn: 'button', buttonImage: '" + imageUrl + "', duration: 0 }); });";
        }

        public static string DateTimePickerJS(this HtmlHelper helper, string name, System.Web.UI.Page page)
        {
			return helper.DatePickerJS(name, page);
        }

        public static MvcHtmlString TextBox(this HtmlHelper helper, string name, object value, string cssClass, string width, string maxLength, bool readOnly, string readOnlyCssClass, bool isMultiLine, string height, bool isPassword)
        {
            IDictionary<string, object> htmlAtts = new Dictionary<string, object>();
            string finalCssClass = null;
            if (!string.IsNullOrEmpty(cssClass))
            {
                finalCssClass = cssClass;
            }
            if (!string.IsNullOrEmpty(width))
            {
                htmlAtts.Add("size", width);
                htmlAtts.Add("style", string.Format("width: {0}em;", width));
            }
            if (!string.IsNullOrEmpty(maxLength))
            {
                htmlAtts.Add("maxLength", maxLength);
            }
            if (readOnly)
            {
                htmlAtts.Add("readonly", "readonly");
                if (!string.IsNullOrEmpty(readOnlyCssClass))
                {
                    if (!string.IsNullOrEmpty(finalCssClass))
                    {
                        finalCssClass += " " + readOnlyCssClass;
                    }
                    else
                    {
                        finalCssClass =  readOnlyCssClass;
                    }
                }
            }
            if (!string.IsNullOrEmpty(finalCssClass))
            {
                htmlAtts.Add("class", finalCssClass);
            }

            return helper.TextBox(name, value, htmlAtts);
        }

        public static MvcHtmlString ValidationMessage(this HtmlHelper helper, string modelName, string validationMessage, string cssClass)
        {
            IDictionary<string, object> htmlAtts = new Dictionary<string, object>();
            if (!string.IsNullOrEmpty(cssClass))
            {
                htmlAtts.Add("class", cssClass);
            }
            return helper.ValidationMessage(modelName, validationMessage, htmlAtts);
        }

        public static string ImageAction(this HtmlHelper helper, UrlHelper urlHelper, string imageRelativePath, string imageAlt, string actionName, System.Web.UI.Page page)
        {
			string imageUrl = GeneralFunctions.GetThemePath(page) + "Images/" + imageRelativePath;
            return string.Format("<a href=\"{0}\"><img src=\"{1}\" alt=\"{2}\" style=\"border-style: none;\" /></a>", urlHelper.Action(actionName), imageUrl, imageAlt);
        }

        public static MvcHtmlString DropDownList(this HtmlHelper helper, string name, DataTable table, string valueColumn, string descriptionColumn, object selectedValue, bool addEmptyValue, string onChange, string style, bool readOnly)
        {
            List<SelectListItem> list = new List<SelectListItem>();
            if(addEmptyValue)
            {
                AddDropDownListEmptyValue(selectedValue, list);          
            }
            if (table != null)
            {
                foreach (DataRowView row in table.DefaultView)
                {
                    SelectListItem item = new SelectListItem();
                    item.Value = row[valueColumn].ToString();
                    item.Text = row[descriptionColumn].ToString();
                    if (selectedValue != null && selectedValue.Equals(row[valueColumn]))
                    {
                        item.Selected = true;
                    }
                    list.Add(item);
                }
            }
            IDictionary<string, object> htmlAtts = GetDropDownListHtmlAtts(onChange, style, readOnly);
            return helper.DropDownList(name, list, htmlAtts);
        }

        private static void AddDropDownListEmptyValue(object selectedValue, List<SelectListItem> list)
        {
            SelectListItem item = new SelectListItem();
            item.Value = "";
            item.Text = "";
            if (selectedValue == null)
            {
                item.Selected = true;
            }
            list.Insert(0, item);
        }

        private static IDictionary<string, object> GetDropDownListHtmlAtts(string onChange, string style, bool readOnly)
        {
            IDictionary<string, object> htmlAtts = new Dictionary<string, object>();
            if (!string.IsNullOrEmpty(onChange))
            {
                htmlAtts.Add("onchange", onChange);
            }
            if (!string.IsNullOrEmpty(style))
            {
                htmlAtts.Add("style", style);
            }
            if (readOnly)
            {
                htmlAtts.Add("disabled", "disabled");
            }
            htmlAtts.Add("class", "formText");
            return htmlAtts;
        }

        public static MvcHtmlString DropDownList(this HtmlHelper helper, string name, List<SelectListItem> list, object selectedValue, bool addEmptyValue, string onChange, string style, bool readOnly)
        {
            if (selectedValue != null)
            {
                foreach (SelectListItem item in list)
                {
                    if (selectedValue.ToString().Equals(item.Value))
                    {
                        item.Selected = true;
                    }
                }
            }
            if (addEmptyValue)
            {
                AddDropDownListEmptyValue(selectedValue, list);
            }
            IDictionary<string, object> htmlAtts = GetDropDownListHtmlAtts(onChange, style, readOnly);
            return helper.DropDownList(name, list, htmlAtts);
        }
    }

    /*public class CustomViewUserControl<T> : ViewUserControl<T> where  T : class
    {
        protected void Page_Init()
        {
            //Page.Theme = "Default";
        }
    }*/
}
